package com.ruoyi.project.digital.service.impl;

import java.io.IOException;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringRandomUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.project.digital.domain.*;
import com.ruoyi.project.digital.domain.dto.FastGptDto;
import com.ruoyi.project.digital.domain.dto.LoginWechatUser;
import com.ruoyi.project.digital.domain.dto.MessageDto;
import com.ruoyi.project.digital.domain.enums.MessageIsLikeEnum;
import com.ruoyi.project.digital.domain.enums.MessageTypeEnum;
import com.ruoyi.project.digital.domain.enums.YesOrNoStatus;
import com.ruoyi.project.digital.domain.vo.PetMessageDetailsVO;
import com.ruoyi.project.digital.service.*;
import com.ruoyi.project.digital.util.HttpClientUtils;
import com.ruoyi.project.digital.util.gpt.GptUtils;
import com.ruoyi.project.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.digital.mapper.PetMessageDetailsMapper;

/**
 * 用户与宠物的聊天详情Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-01
 */
@Service
public class PetMessageDetailsServiceImpl extends ServiceImpl<PetMessageDetailsMapper, PetMessageDetails> implements IPetMessageDetailsService {

    @Autowired
    private IPetMessageService petMessageService;

    @Autowired
    private IPetMessageDetailsService petMessageDetailsService;

    @Autowired
    private ITaskService taskService;

    @Autowired
    private IUserTaskService userTaskService;


    @Autowired
    private WechatUserTokenService wechatUserTokenService;

    @Autowired
    private ITUserService userService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IPetService petService;

    /**
     * 查询用户与宠物的聊天详情
     *
     * @param id 用户与宠物的聊天详情ID
     * @return 用户与宠物的聊天详情
     */
    @Override
    public PetMessageDetails selectPetMessageDetailsById(Long id) {
        return baseMapper.selectPetMessageDetailsById(id);
    }

    /**
     * 查询用户与宠物的聊天详情列表
     *
     * @param petMessageDetails 用户与宠物的聊天详情
     * @return 用户与宠物的聊天详情
     */
    @Override
    public List<PetMessageDetails> selectPetMessageDetailsList(PetMessageDetails petMessageDetails) {
        return baseMapper.selectPetMessageDetailsList(petMessageDetails);
    }

    /**
     * 新增用户与宠物的聊天详情
     *
     * @param petMessageDetails 用户与宠物的聊天详情
     * @return 结果
     */
    @Override
    public int insertPetMessageDetails(PetMessageDetails petMessageDetails) {
        petMessageDetails.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertPetMessageDetails(petMessageDetails);
    }

    /**
     * 修改用户与宠物的聊天详情
     *
     * @param petMessageDetails 用户与宠物的聊天详情
     * @return 结果
     */
    @Override
    public int updatePetMessageDetails(PetMessageDetails petMessageDetails) {
        return baseMapper.updatePetMessageDetails(petMessageDetails);
    }

    /**
     * 批量删除用户与宠物的聊天详情
     *
     * @param ids 需要删除的用户与宠物的聊天详情ID
     * @return 结果
     */
    @Override
    public int deletePetMessageDetailsByIds(Long[] ids) {
        return baseMapper.deletePetMessageDetailsByIds(ids);
    }

    /**
     * 删除用户与宠物的聊天详情信息
     *
     * @param id 用户与宠物的聊天详情ID
     * @return 结果
     */
    @Override
    public int deletePetMessageDetailsById(Long id) {
        return baseMapper.deletePetMessageDetailsById(id);
    }

    @Override
    public List<PetMessageDetailsVO> nearMessageList(Long userId) {

        QueryWrapper<PetMessage> q = new QueryWrapper<>();
        q.select("MaX(id)");
        q.eq("user_id", userId);

        List<Object> result = petMessageService.listObjs(q);
        Long messageId = null;
        if (!result.isEmpty()) {
            messageId = Long.valueOf(result.get(0).toString());
            messageId = Long.valueOf(messageId);
        }
        if (null != messageId) {
            QueryWrapper<PetMessageDetails> q1 = new QueryWrapper<>();
            q1.select("*");
            q1.eq("message_id", messageId);
            return baseMapper.nearMessageList(q1);
        }
        return null;
    }

    @Override
    public List<PetMessageDetailsVO> messageDtails(Long messageId) {
        QueryWrapper<PetMessageDetails> q1 = new QueryWrapper<>();
        q1.select("*");
        q1.eq("message_id", messageId);
        return baseMapper.nearMessageList(q1);
    }

    /**
     * 喜欢的消息类型
     *
     * @param id
     */
    @Override
    public void likeMessage(Long id) {
        PetMessageDetails details = new PetMessageDetails();
        details.setId(id);
        details.setIsLike(MessageIsLikeEnum.LIKE.getValue());
        updateById(details);
    }

    /**
     * 不喜欢的消息类型
     *
     * @param id
     */
    @Override
    public void noLikeMessage(Long id) {
        PetMessageDetails details = new PetMessageDetails();
        details.setId(id);
        details.setIsLike(MessageIsLikeEnum.NO_LIKE.getValue());
        updateById(details);
    }

    @Override
    public PetMessageDetails sendMessge(MessageDto dto) throws IOException {
        LoginWechatUser loginMember = wechatUserTokenService.getLoginWechatUser(ServletUtils.getRequest());

        FastGptDto fastGptDto=getFastGptDto(dto,loginMember);
        String result=  HttpClientUtils.getMessage(fastGptDto);
        PetMessageDetails details = new PetMessageDetails();
        details.setType(MessageTypeEnum.USER.getValue());
        details.setMessageId(dto.getMessageId());
        details.setContent(dto.getMessage());
        details.setIsRead(YesOrNoStatus.YES.getValue().toString());
        details.setCreateBy(String.valueOf(loginMember.getId()));
        save(details);
        details.setType(MessageTypeEnum.PET.getValue());
        details.setContent(result);
        if (ObjectUtil.isNull(details.getContent())) {
            details.setContent("AI好像生病休息了，等会再来吧！");
        }
        details.setMessageId(dto.getMessageId());
        save(details);
        PetMessage petMessage = petMessageService.selectPetMessageById(dto.getMessageId());
        if (ObjectUtil.isNull(petMessage.getTitle())) {
            petMessage.setTitle(dto.getMessage());
            petMessage.setSubTitle(dto.getMessage() + "-" + details.getContent());
            petMessageService.updateById(petMessage);
        }
        handlerUser(null);
        // 统计聊天次数
        QueryWrapper<PetMessageDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_by",loginMember.getId()).eq("type","0");
        int count = petMessageDetailsService.count(queryWrapper);
        if (count > 99){
            UpdateWrapper<UserTask> userTaskQueryWrapper = new UpdateWrapper<>();
            userTaskQueryWrapper.eq("title","聊天").eq("user_id",loginMember.getId());
            userTaskQueryWrapper.set("status","1");
            userTaskService.update(userTaskQueryWrapper);
            QueryWrapper<Task> taskQueryWrapper = new QueryWrapper<>();
            taskQueryWrapper.eq("title","聊天");
            Task task = taskService.getOne(taskQueryWrapper);
            handlerUser(task.getGetValue());
        }
        return details;
    }

    private FastGptDto getFastGptDto(MessageDto dto, LoginWechatUser loginMember) {
        FastGptDto fastGptDto=new FastGptDto();
        PetMessage petMessage=petMessageService.selectPetMessageById(dto.getMessageId());
        Pet  pet=petService.selectPetById(petMessage.getPetId());
        TUser user=userService.selectTUserById(loginMember.getId());
        fastGptDto.setUserName(user.getNickName());
        fastGptDto.setApiKey(pet.getApiKey());
        fastGptDto.setContent(dto.getMessage());
        fastGptDto.setBaseUrl(pet.getBaseUrl());
        return fastGptDto;
    }

    /**
     * 处理体力值业务
     */
    private void handlerUser(Long value) {
        LoginWechatUser loginMember = wechatUserTokenService.getLoginWechatUser(ServletUtils.getRequest());
        TUser user = userService.getById(loginMember.getId());
        String key = sysConfigService.selectConfigByKey(Constants.RES_STAMINA);
        if (null != value){
            TUser tUser = new TUser();
            tUser.setId(user.getId());
            tUser.setResStamina(user.getStamina() + value);
        }else {
            TUser tUser = new TUser();
            tUser.setId(user.getId());
            tUser.setResStamina(user.getStamina() - Integer.valueOf(key));
            userService.updateById(tUser);
        }
    }
}
